import React, { useState, useRef, useEffect } from 'react'
import { Tooltip } from 'antd'
import list2tree from 'list2tree'
import { connect } from '@umijs/max'
import {
  ProTable, ProTableOptions, InputSearch, BreadcrumbBar, ProTableOperate, ProTree, searchTreeListByName,
} from '@/components'
import { BindDetail } from './page-components'
import styles from './index.less'

const { OperateItem } = ProTableOperate

const menus = [{ name: '标准设计' }, { name: '标准映射' }]

const getNavTreeDataFunc = list2tree({
  idKey: 'id',
  parentIdKey: 'pid',
  newKey: {
    key: 'id',
    value: 'id',
    title: 'themeName',
  },
})

// 获取该id下所有的子id
const getAllChildrenId = (dataRef) => {
  const tempArr = [dataRef.id]
  if (dataRef.children) {
    dataRef.children.map((item) => {
      // eslint-disable-next-line prefer-spread
      tempArr.push.apply(tempArr, getAllChildrenId(item))
      return null
    })
  }
  return tempArr
}

const StandardMap = (props) => {
  const bindDetailRef = useRef()
  const [treeData, setTreeData] = useState([])
  const [treeDataNew, setTreeDataNew] = useState([])
  const [selectedKeys, setSelectedKeys] = useState([])
  const [inpValue, setInpValue] = useState('')
  const [query, setQuery] = useState({})
  const [forceUpdate, setForceUpdate] = useState(0)
  const [timeStr, setTimeStr] = useState('')
  let tree

  useEffect(() => {
    getTreeThemes()
    getLastCheckTime()
  }, [])

  useEffect(() => {
    if (inpValue === '') {
      fetchData()
    }
  }, [inpValue])

  // 获取左侧列表方法
  const getTreeThemes = () => {
    // 标记每个节点是第几层children
    const signLayerNum = (item, num = 0) => {
      item.layerNum = num
      if (num >= 5) {
        item.icon = true
      }
      item?.children?.map((child) => {
        const tempNum = num + 1
        signLayerNum(child, tempNum)
        return null
      })
    }
    props.dispatch({
      type: 'standardDefine/dictionaryGroupList',
      cb: (data) => {
        const arr = getNavTreeDataFunc(data) || []
        // 给tree的数据标上第几层children
        arr.map((item) => {
          signLayerNum(item)
          return null
        })
        setTreeData(data || [])
        setTreeDataNew(arr)
      },
    })
  }

  // 获取最近检测时间
  const getLastCheckTime = () => {
    props.dispatch({
      type: 'standardMap/queryGetLastTaskExecuteTime',
      cb: (data) => {
        setTimeStr(data || '')
      },
    })
  }

  const columns = [
    {
      title: '中文名称',
      dataIndex: 'dictNameCn',
      key: 'dictNameCn',
      width: '16%',
    },
    {
      title: '英文名称',
      dataIndex: 'dictNameEn',
      key: 'dictNameEn',
      sorter: true,
      width: '16%',
    },
    {
      title: '待绑定数量',
      dataIndex: 'notBoundCount',
      key: 'notBoundCount',
      sorter: true,
      width: '14%',
    },
    {
      title: '已绑定数量',
      dataIndex: 'boundCount',
      key: 'boundCount',
      sorter: true,
      width: '14%',
    },
    {
      title: '最近筛查时间',
      dataIndex: 'updateTime',
      key: 'updateTime',
      sorter: true,
      width: '18%',
    },
    {
      title: '创建人',
      dataIndex: 'creatorName',
      key: 'creatorName',
      width: '10%',
    },
    {
      title: '操作',
      // dataIndex: 'space',
      key: 'operate',
      render: (record) => {
        const { dictId } = record
        return (
          <ProTableOptions>
            <span onClick={() => { bindDetailRef?.current?.toggleModal(dictId) }}>绑定详情</span>
          </ProTableOptions>
        )
      },
    },
  ]

  const onSelect = (selectedKeysParams, node) => {
    setSelectedKeys(getAllChildrenId(node.node))
    setQuery({
      ...query,
      dictDirIds: getAllChildrenId(node.node).join(','),
    })
  }

  const fetchData = () => {
    const tempQuery = {}
    tempQuery.search = inpValue
    setQuery({
      ...query,
      ...tempQuery,
      dictDirIds: selectedKeys.join(','),
    })
  }

  const forceUpdateFn = () => {
    setForceUpdate(forceUpdate + 1)
  }

  return (
    <div className={styles.standard_map}>
      <BreadcrumbBar menu={menus} />
      <div className={styles.page_content}>
        <div className={styles.page_content_left}>
          <ProTree
            showLine
            showSearch
            width={208}
            showTitle={false}
            treeData={treeDataNew}
            selectedKeys={selectedKeys}
            onSelect={onSelect}
            ref={(dev) => (tree = dev)}
            search={(name) => {
              const searchTree = searchTreeListByName(
                name,
                treeData,
                'themeName',
              )
              const treeDataNews = getNavTreeDataFunc(
                searchTree.result,
              )
              setTreeDataNew(treeDataNews)
              tree.onExpand(searchTree.fatchIds)
            }}
          />
        </div>
        <div className={styles.page_content_right}>
          <ProTableOperate>
            <OperateItem align="left">
              <InputSearch
                placeholder="请输入中文名称或英文名称进行搜索"
                value={inpValue}
                onChange={(e) => {
                  setInpValue(e.target.value)
                }}
                onSearch={fetchData}
              />
            </OperateItem>
            {/* // 占位 */}
            <OperateItem />
            {timeStr ? (
              <OperateItem>
                <div className={styles.time_str}>
                  <Tooltip
                    placement="top"
                    title="标准映射24小时测一次"
                  ><i className="iconfont icon-shijian" />
                  </Tooltip>
                  {`最近检测时间: ${timeStr}`}
                </div>
              </OperateItem>
            ) : null}
          </ProTableOperate>
          <ProTable
            key={forceUpdate}
            loading={false}
            rowKey={() => String(Math.random())}
            query={query}
            url="/api/v1/mapping/list"
            columns={columns}
          />
        </div>
      </div>
      <BindDetail
        ref={bindDetailRef}
        forceUpdateFn={forceUpdateFn}
      />
    </div>
  )
}

export default connect(({ standardMap }) => ({ ...standardMap }))(StandardMap)
